/*
 * WebServiceClient.java
 *
 * Created on February 18, 2008, 3:31 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package com.computec.encolador.service.client;



import com.computec.encolador.constantes.ConstantesGenerales;
import java.util.Iterator;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
/**
 *
 * @author fsanchez
 */
public class WebServiceClient {
    static WebServiceClient currentInstance;
    /** Creates a new instance of WebServiceClient */
    private WebServiceClient() {
	ConstantesGenerales.getInstance();
    }
    
    public static WebServiceClient getInstance(){
	if(currentInstance==null){
	    currentInstance=new WebServiceClient();
	}
	return currentInstance;
    }

    public boolean invokeService(String command) throws Exception {
        ServiceClient client = new ServiceClient();
        // create option object
        Options opts = new Options();
        //setting target EPR
        opts.setTo(new EndpointReference(ConstantesGenerales.ENDPOINT_REFERENCE));
        //Setting action ,and which can be found from the wsdl of the service
        opts.setAction("urn:"+ConstantesGenerales.ACTION);
        client.setOptions(opts);
        Boolean b=new Boolean(false);
        OMElement res=null;

	res = client.sendReceive(createPayLoad(command));
	     
	if(res!=null){
	    Iterator it=res.getChildElements();
	    for(;it.hasNext();){
		    OMElement o=(OMElement)it.next();        	
		    b=new Boolean(o.getText());
	    }
	    System.out.println(res);
	}
	System.out.println("Ejecuto:"+b);
	return b.booleanValue();
    }

    public static OMElement createPayLoad(String command) {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace(ConstantesGenerales.NAMESPACE, "ns1");
        OMElement method = fac.createOMElement(ConstantesGenerales.ACTION, omNs);
        OMElement value = fac.createOMElement("value", omNs);
        value.setText(command);
        method.addChild(value);
        return method;
    }   
}
